package com.senyint.sys.utils.crypto;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class RSA {

    public static KeyPair genKey() throws NoSuchAlgorithmException {
        // 生成密钥对
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(512);
        return keyPairGenerator.generateKeyPair();
    }

    public static String encode(PrivateKey rsaPrivateKey, String content) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidKeySpecException {
        //私钥
//            RSAPrivateKey rsaPrivateKey = (RSAPrivateKey)genKey().getPrivate();
        // 格式化私钥
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);

        Cipher cipher = Cipher.getInstance("RSA");  // 确定算法// 私钥
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);  // 确定加密密钥
        // 进入加密模式
        byte[] result = cipher.doFinal(content.getBytes());
        return Base64.getEncoder().encodeToString(result);
    }

    public static String decode(PublicKey rsaPublicKey, String encodeContent) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidKeySpecException {
        //公钥
//            RSAPublicKey rsaPublicKey = (RSAPublicKey)genKey().getPublic();
        // 格式化公钥
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded());
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);

        Cipher cipher = Cipher.getInstance("RSA"); // 确定算法
        cipher.init(Cipher.DECRYPT_MODE, publicKey);  // 确定公钥
        return new String(cipher.doFinal(Base64.getDecoder().decode(encodeContent)));
    }

    public static void main(String[] args) throws NoSuchPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, InvalidKeySpecException {
        String pwd = "abc";
        KeyPair keyPair = RSA.genKey();
        String encoder = RSA.encode(keyPair.getPrivate(), pwd);
        System.out.println(encoder);
        System.out.println(RSA.decode(keyPair.getPublic(), encoder));
    }
}

